package io.openmessaging.utils;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author cuijd    2021/9/14 10:43
 */
public class Log {
    private static long startTime = System.currentTimeMillis();
    private static ThreadLocal<StringBuilder> lsb = new ThreadLocal<>();

    public static void i(Object... param) {
        StringBuilder sb = lsb.get();
        if (sb == null)
            lsb.set(sb = new StringBuilder());

        sb.setLength(0);
        sb.append(Strings.leftPad((System.currentTimeMillis() - startTime), 6)).append(" ");
        sb.append(Strings.leftPad(Thread.currentThread().getName(), 10)).append(" ");
        for (Object o : param) {
            sb.append(o);
        }
        Assert.isTrue(queue.offer(sb.toString()), "offer fail!");
    }

    static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

    static {
        new Thread(() -> {
            try {
                while (true) {
                    String s = queue.poll();
                    if (s == null)
                        Thread.sleep(1);
                    else
                        System.out.println(s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("ShutdownHook=========================");
            while (!queue.isEmpty())
                System.out.println(queue.poll());
        }));
    }

}
